<html xmlns="http://www.w3.org/1999/xhtml" id="constraints"
      xmlns:d="docbook">
<head>
    <title>Constraints</title>
</head>

<body>
 
<h1>Constraints</h1>

<h2>Constraints defined</h2>

<p>In LZX, a <dfn>constraint</dfn> is an attribute whose value is a
function of other attribute values.</p>

<p>Constraints help you quickly create dependencies without writing a
lot of code. You can specify that certain views are the same size or
positioned relative to one another. Specific elements can appear only
under certain condition; and those conditions may be declared with a
simple expression. Constraints may be used for non-visual attributes
as well.</p>

<h2>Syntax for creating and removing constraints</h2>
<p>Constraints may be created in either of two ways:</p>
<ul>
	<li>in a tag, using the ${} syntax to tie the value of one attribute to that of another</li>
	<li>in script, using the <method>applyConstraint</method> method</li>
    <li>in script, using delegates</li>
</ul>
<p>These are described in turn below.</p>
<p>There is no method for removing constraints.  Therefore if you have a constraint that you wish to sometimes be in force and other times not be in force, you should use <tagname link="true">state</tagname>s.</p>

<h3>Creating Constraints in Tags</h3><!-- There's a copy of this next section in language-preliminaries.  Change that if you change this. -->

<p>The syntax for coding a constraint is:</p> 

<pre>$<i>when</i>{<i>expression</i>}</pre>

<p>where:</p>
<ul>
  <li><code>$</code> is the token indicating a constraint</li>
  
  <li><code><i>when</i></code> is an optional compiler directive:
  <code>immediately</code>, <code>once</code>, or <code>always</code>.
  <code>$always{<i>expression</i>}</code> can be abbreviated to
  <code>${<i>expression</i>}</code> </li>
  
  <li><code>{</code> and <code>}</code> are tokens delimiting the
  expression to be evaluated</li>
  
  <li><code><i>expression</i></code> is a JavaScript expression</li>
</ul>
<h3>Creating constraints from script</h3> 

<fixme> note the lousy explanation below </fixme>

<p>The following example uses the <method>applyConstraint</method> method inherited from <classname>LzNode</classname> in order to create a constraint at
runtime. You'll see that the <code>setConstraint</code> method has the same effect as the simple expression <code>y=${m.y}</code>
</p>

<example title="Runtime constraints with applyConstraint">
&lt;canvas&gt;
  &lt;view x="250" width="20" height="20" bgcolor="red"
        y="${m.y}"/&gt;

  &lt;view x="300" width="20" height="20" bgcolor="blue"&gt;  
    &lt;method name="setConstraint" event="oninit"&gt;
      var f = function () {   
        this.setAttribute("y", m.y);       
      }
      var d = [m, "y"];
      this.applyConstraint("y", f, d);
    &lt;/method&gt;
  &lt;/view&gt;

  &lt;window id="m" x="10" title="Drag me" width="160" height="20"/&gt;  
&lt;/canvas&gt;

</example>

<p><code>f</code> is a callback function that is required for the <method>applyConstraint</method> method. <varname>d</varname> 
is an array consisting of a pointer to a reference node, and the attribute to bind to.</p>
<h3>Delegates and constraints</h3> 
<p>Laszlo applications can use something called a <glossterm>delegate</glossterm> in script to associate a 
method or any global function with an event.  When the event is triggered, the method is called.</p>

<p>
The above constraint expression could also be written in script as:
</p>

<example executable="false">
&lt;method event="oninint"&gt;
  var width_del = new LzDelegate(this, "updateMyWidth");
  width_del.register(parent, "onwidth");
&lt;/method&gt;
  
&lt;method name="updateMyWidth"&gt;
  this.setWidth(parent.width);
&lt;/method&gt;
</example>
<p>
You can read more about delegates in <xref linkend="delegates"/>.
</p>
<h3>States: a quick look</h3>
<p>States are a convenient way to set and remove constraints at runtime.</p>
<p>You create states using the <tagname link="true">state</tagname> tag, for example:</p>
<example extract="false" title="states and constraints">
&lt;state name="flexistate"&gt;
    &lt;attribute name="width" value="${parent.width}" /&gt;
&lt;/state&gt;

&lt;state name="boringstate" apply="false"&gt;
    &lt;attribute name="width" value="50" /&gt;
&lt;/state&gt;
</example>
<p>States are further explained in <xref linkend="states"/>.</p>
<h2>Constraints in action</h2>
<p>Whenever the value of an attribute changes, its <event>on</event>
event is generated. Because a constraint is an attribute whose value
is dependent upon the values of one or more other attribute(s), the
value of the constraint is recalculated whenever it receives the
<event>on</event> event for the attributes on which it depends. </p>

<p>Consider</p> 
<example executable="false"> 
&lt;view name="someView" 
   width="${someAttribute + someOtherAttribute}" 
   /&gt; 
</example>

<p>Then the value of <code>someView.width</code> would be recomputed whenever an <event>onsomeAttribute</event> or <event>onsomeOtherAttribute</event> event occurred.</p> 

<p>So for example</p> 
<example executable="false">
&lt;view name="beatles" width="${this.paul.width + 28}"&gt;
   &lt;view name="paul" onclick="clickhandler()"&gt;
      &lt;!-- clickhandler method here to increase paul's width based on user clicking mouse --&gt;
   &lt;/view&gt;
&lt;/view&gt;
</example>

<p>The width of <varname>beatles</varname> will increase or
decrease as a function of <varname>paul</varname>'s width;
the expression <code>this.paul.width + 28</code> is a constraint.</p>

<p>This is a trivial
example, but it serves to make the point that in declaring the
structure of your objects in LZX you also declare the rules by which
they will relate to each other. Constraints are a fundamental concept
in LZX programming, and learning to "think in LZX" is a
mostly a matter of learning to properly model your system's behavior
in terms of the constraints on its constituent parts.</p>

<h3>Modeling real system constraints</h3>

<p>You can think about constraints as modeling real system interrelationships.  A constraint
expression can establish that two objects are connected.</p>

<p>In the example below, the visibility of the blue square is
connected to the value of the checkbox.  When you toggle the checkbox,
the visibibility of the blue square automatically switches as
well.</p>

<example title="An element appears when a checkbox is set"
         id="ex.constraints.1">
&lt;canvas height="120"&gt;
  &lt;checkbox id="cb" text="Show Blue Square"/&gt;
  &lt;view visible="${cb.value}"
        width="30" height="30" bgcolor="blue"/&gt;
  &lt;simplelayout/&gt;
&lt;/canvas&gt;
</example>

<p>In the example below, the position of the blue square is connected
to the position of the mouse.  If you move the mouse inside the
canvas, the blue square will move as the mouse moves, floating
relative to the position of the mouse.  In this case, the constraint
expression includes a method call, but it works in the same way as the
simple attribute expression in <xref linkend="ex.constraints.1"/>.</p>

<example title="Constrain to Mouse Position"
         id="ex.constraints.2">
&lt;canvas height="120"&gt;
  &lt;view bgcolor="blue" width="40" height="40"
        x="${parent.getMouse('x')}"
        y="${parent.getMouse('y')}"/&gt;
&lt;/canvas&gt;
</example>

<p>The constraint expression may be any Javascript expression.  For
example, you could change the y value in example <xref
linkend="ex.constraints.1"/> to
<code>y="${immediateParent.getMouse('y')+10}"</code> and cause the
blue square to float below the mouse.  If you centered the blue square
at the mouse position by setting the y value with
<code>y="${immediateParent.getMouse('y') - this.width/2}"</code>
&#x2014; if the width of the blue square changes, the y value with be
updated to position the blue square relative to the new width and the
mouse position.</p>

<h2>Events and Dependencies</h2> 

<p>Every constraint has one or more dependencies.  For example, the constraint expression:</p>

<example executable="false">
width="${parent.width}"
</example>

<p>creates a dependency on the parent's width attribute.  As explained
in <xref linkend="methods-events-attributes"/>, whenever an attribute
is set by calling <code>setAttribute('whatever', 4) </code> an
<event>onwhatever</event> event is sent.  Following the above example
for the <attribute>width</attribute> attribute, an
<event>onwidth</event> event is sent whether the attribute has been
set with <code>setAttribute, setWidth()</code> or by another
constraint.</p>

<p>When you use a constraint expression, a function is automatically
generated to set the value of the attribute.  That function is then
called whenever an event is triggered on which the constraint has a
dependency.</p>


<h2>Multiple Dependencies</h2> 

<p>Constraints can have dependencies on multiple attributes.  In the code below, the <attribute>width</attribute> attribute
is dependent on the immediateparent's <code>width</code> attribute and the parent's <code>bordersize</code> attribute.  When either attribute is 
set the <attribute>width</attribute> updates. Immediateparent.width is used instead of parent.width, because immediateparent, in this case, is the interior view of the window, while parent is the whole window.</p>

<example executable="false">
width="${immediateparent.width - parent.bordersize * 2}"
</example>

<p>Experiment with the working example below to see multiple dependencies in action.  Resizing the window
will resize the blue bar.  You can also move the slider to adjust the border size.</p>

<example title="Multiple Dependencies">
&lt;canvas height="300" width="700"&gt;
  &lt;window width="400" height="200" resizable="true"&gt;
    &lt;attribute name="bordersize" value="${editor.bordersize.value}"/&gt;
    &lt;view y="20" name="editor" layout="axis:x; spacing:10; inset:10"&gt;
      &lt;text y="-4" resize="true"&gt;bordersize:&lt;/text&gt;
      &lt;slider name="bordersize" value="10"/&gt;
    &lt;/view&gt;

    &lt;view bgcolor="0xFFC834" y="80"
          width="${immediateparent.width}" height="10" /&gt;
    &lt;view x="${parent.bordersize}" y="80"
             width="${immediateparent.width - parent.bordersize * 2}"
             height="10" bgcolor="blue" /&gt;
    
  &lt;/window&gt;
&lt;/canvas&gt;
</example>

<h2>Circular Constraints</h2> 

<p>A constraint loop exists when the value of an attribute <varname>A</varname> depends on <varname>B</varname>, and <varname>B</varname> depends on <varname>A</varname>. 
It's actually a very natural thing to do in LZX.
For example, in the Laszlo application below, the <code>y</code> values of the red and blue squares are constrained to each other.
</p>

<example class="code" title="Circular Constraints">
&lt;canvas height="120"&gt;
  &lt;view name="redview" bgcolor="red"
        onmousedown="gragger.apply()" onmouseup="gragger.remove()"
        width="40" height="40" y="${blueview.y}"&gt;
    &lt;dragstate name="gragger"/&gt;
  &lt;/view&gt;
  &lt;view name="blueview" bgcolor="blue"
        onmousedown="gragger.apply()" onmouseup="gragger.remove()"
        width="40" height="40" y="${redview.y}"&gt;
    &lt;dragstate name="gragger"/&gt;
  &lt;/view&gt;
  &lt;simplelayout spacing="40" axis="x"/&gt;
&lt;/canvas&gt;
</example>

<p>
How does it work?  When you drag
the red view to change its on y position, it sends an <event>ony</event> event.  The blue view is listening for the
red view's <event>ony</event> event and responds by updating its own y position.  The red view is listening
for the blue view's <event>ony</event> event; however, it doesn't respond to that event because an event handler only gets 
called one time on each event.</p>

<fixme>
That above explanation is pretty lame.
</fixme>

<h2>Performance Considerations</h2> 

<p>
Constraints are an effective way to write user interface code and in some case to manage non-visual
application state.  As with any code, you will want to understand the performance implications, as well as
when it is best to use constraints as opposed to alternate methods of achieving similar effects.
</p>

<h3>Declaring When Constraints are to be evaluated</h3>

<p>
Often you will want to use constraint expressions to create the initial state of your application, but 
you don't need attributes to update dynamically while the application is in use.  In the case, you
can improve startup time performance by declaring <code>when</code> the expression should be evaluated.
</p>

<fixme>
Need a table of values for when
</fixme>

<p>When you write a constraint using the <code>${...}</code> syntax (as in the example below),  <code>when="always"</code> is the default.</p>

<pre>
&lt;view width="${parent.width}" height="10" bgcolor="yellow"/&gt;
</pre>

<p>To optimize this expression for the case when the dependency will not change, you will want to
specify <code>when="once"</code>:</p>

<pre class="code">
&lt;view width="$once{parent.width}" height="10" bgcolor="yellow"/&gt;
</pre>

<p>When declaring class attributes, the attribute is typically declared using
  an <tagname>attribute</tagname> tag, where the <code>when</code> value may be declared explicitly:</p>

<pre>
&lt;class name="myclass"&gt;
  &lt;attribute name="width" value="${parent.width}" when="once"/&gt;
&lt;/class&gt;
</pre>

<p>
In this case if <code><i>when</i></code> is not specified, the value is <code>immediately</code>,
which means that it initializes the attribute to the value of the expression
when the enclosing element is defined. The value must be a constant expression
and
cannot
depend on any other objects.</p>

<h3>When to use Layouts instead of Constraints</h3>
<p>
Constraints can be very useful for positioning and determining the size of views.  However, if you 
have a large number of views updating based on the same information, it is better to use a <tagname link="true">layout</tagname>
instead of writing a complex constraint system. 
There are quite a few layouts available with LPS and you can write your own. See <xref linkend="layout-and-design"/> for more 
on this subject.
</p>

<h3>When to events and methods instead of constraints</h3> 

<p>Generally, if you have a lot of different things that need to be updated based on a single dependency, it
is optimal to write a setter for the dependent attribute and in that setter take appropriate actions.</p>



<?ignore
<fixme>
It would be good to include info about 
 "<a href="http://www.laszlosystems.com/developers/community/forums/showthread.php?s=&amp;threadid=497">constraints with 
variable targets</a>"
</fixme>


<h4>Constraints derived from datapaths</h4>
<p>
The <code>$path{'<varname>expression</varname>'}</code> syntax is used to signify the value returned by evaluating the XPath expression within the braces (note the single quotes enclosing the XPath expression. For example:</p>

<pre> 
&lt;textlistitem datapath="mydata:/list/item" text="$path{'text()'}" value="$path{'@value'}"/&gt;
</pre>
<fixme>
 say something about ${path} syntax and put in a link to Adam's chapter
</fixme>

<fixme> Example: using constraints for layout  -- forward reference to layout chapter, building your own layout
</fixme>
<fixme>
ii.	The "video player" example
1.	Original design constraint as Method
2.	Better design
iii.	The "shadow box" example  (This is from Tucker's AppWeek report --instructive example of doing the same thing with and without constraints)
1.	procedural version
2.	Constraint-based version
</fixme>
<fixme>
<p>

more stuff for performance section:
iv.When NOT to use constraints
1.performance analysis comparing constraints and layouts
2.optimization difficult if too many intersecting dependencies
 Summary: powerful, but excessive use of constraints can make program hard to understand/maintain
</p>
 </fixme>
<fixme>


  Why should the defaults for "when" be different, depending on whether you use the ${} syntax or not?

This matches the use of ${} in an inline attribute:
 &lt;view width="100"
has an $immediately when;
 &lt;view width="${expr}"
has an $always when.

Similarly:
 &lt;view&gt;
   &lt;attribute name="width" value="100"/&gt;
is $immediately;
 &lt;view&gt;
   &lt;attribute name="width" value="${expr}"
</fixme>
?>


<h2>Constraints and Functions</h2>
<p>
Take care when using JavaScript functions inside of constraints.
</p>
<p>
In general, there are only a limited number of LZX functions that have  dependency
functions and can be expected to correctly participate in a  constraint. 
No ECMAScript  functions have dependency functions, so none of them will work  properly in a constraint.
</p>
<p>
More precisely, ECMAScript functions will work properly if they are  stateless
(they depend only on the values of their arguments), so, for example,<code>
value="Math.max(parent.width, parent.height)"</code> will do the right thing.   (Any
stateless function works.)  However, many apparently simple functions do not work within constrains.
</p>
<p>Consider</p>
<pre>
     &lt;param value="${escape(canvas.options.serialize())}"/&gt;
</pre>
<p>
in which the value of a parameter is constrained to that returned by a serializing function. 
Upon inspection, we see that he dependencies of </p>

<pre>
     value="escape(canvas.options.serialize())"
</pre>
<p>
 will be calculated as:</p>

 <ul>
	<li>the dependencies of <code>escape</code> (which includes the value of 
<code>canvas.options.serialize())</code></li>
	<li>the dependencies of serialize</li>
</ul>
<p>In  this case, <code>value</code> gets evaluated too early (i.e. before the dataset has any data) 
and that's why you don't see any data. Instead, you would use <method>getValue</method>which acts as 
a getter for &lt;param&gt;, instead of using a constraint.</p>
<p>
In evaluating dependencies in constraints, the OpenLaszlo compiler only look at the 'tail' of a chain, so if you  have
an expression a.b.c, only c will be depended on.  For a function,  the function
itself computes its dependencies, based on its  arguments.  In the case of
<code>escape</code>, it doesn't have a dependency  function, nor does <code>serialize</code>, so in this
particular example, there  will be no dependencies at all.
</p>
<p>
EXCEPT that the constraint mechanism only looks at a tail, so for example NEITHER 
<code>value="parent.selected.width"</code> NOR <code>value="Math.max(parent.width, 
parent.selected.width"</code> will work if <code>parent.selected</code> changes value (it's  fine if
<code>parent.selected </code>stays the same but <code>parent.selected.width </code> changes).  </p>
<p>
The bottom line is that the constraint calculator is not really designed to be used in functions. It
works for many situations, but not for anything complex.</p>
</body>
</html>
<!-- * X_LZ_COPYRIGHT_BEGIN ***************************************************
* Copyright 2001-2004 Laszlo Systems, Inc.  All Rights Reserved.              *
* Use is subject to license terms.                                            *
* X_LZ_COPYRIGHT_END ****************************************************** -->
